import {create} from 'zustand';
import {generateId} from '@/lib/utils';

// Toast消息类型定义
interface ToastMessage {
    id: string;
    message: string;
    type: 'success' | 'error' | 'info' | 'warning';
    duration?: number;
}

// Toast通知状态管理接口
interface ToastState {
    // 通知消息列表
    messages: ToastMessage[];

    // 显示通知
    showToast: (message: string, type?: ToastMessage['type'], duration?: number) => void;
    // 显示成功通知
    showSuccess: (message: string) => void;
    // 显示错误通知
    showError: (message: string) => void;
    // 显示信息通知
    showInfo: (message: string) => void;
    // 显示警告通知
    showWarning: (message: string) => void;

    // 移除指定通知
    removeToast: (id: string) => void;
    // 清空所有通知
    clearAll: () => void;
}


// 默认持续时间配置
const DEFAULT_DURATION = {
    success: 3000,
    error: 5000,
    info: 4000,
    warning: 4000,
};

// 创建Toast状态管理store
export const useToastStore = create<ToastState>((set, get) => ({
    messages: [],

    // 显示通知（通用方法）
    showToast: (message, type = 'info', duration) => {
        const id = generateId();
        const finalDuration = duration ?? DEFAULT_DURATION[type as keyof typeof DEFAULT_DURATION];

        const newMessage: ToastMessage = {
            id,
            message,
            type,
            duration: finalDuration,
        };

        // 添加到消息列表
        set((state) => ({
            messages: [...state.messages, newMessage],
        }));

        // 自动移除通知
        if (finalDuration > 0) {
            setTimeout(() => {
                get().removeToast(id);
            }, finalDuration);
        }
    },

    // 显示成功通知
    showSuccess: (message) => {
        get().showToast(message, 'success');
    },

    // 显示错误通知
    showError: (message) => {
        get().showToast(message, 'error');
    },

    // 显示信息通知
    showInfo: (message) => {
        get().showToast(message, 'info');
    },

    // 显示警告通知
    showWarning: (message) => {
        get().showToast(message, 'warning');
    },

    // 移除指定通知
    removeToast: (id) => {
        set((state) => ({
            messages: state.messages.filter((msg) => msg.id !== id),
        }));
    },

    // 清空所有通知
    clearAll: () => {
        set({messages: []});
    },
}));

